<template>
  <div class="ctea">
    <el-card class="box-card" @click="showScreenPopover = false">
      <template #header>
        <div class="card-header">
          <div class="between">
            <div class="alitem">
              <el-icon @click="onClickBack">
                <ArrowLeftBold />
              </el-icon>
              <span>创建填报方案</span>
              <div class="userInfo" style="margin-left: 10px">
                <span>{{ studentData.studentName }}</span>
                <span>{{ studentInfo.sex == 0 ? '男' : '女' }}</span>

                <span> {{ studentData.gkaProvinceName }}</span>
                <span> {{ studentInfo.score }}分</span>
                <span> {{ studentInfo.section }}位</span>
                <span>{{ studentInfo.sgname }}</span>
                <span>
                  <span>{{ batchInfo.batch }}</span>
                  <!-- <span v-if="batchInfo.type === 1">(普高)</span>
                  <span v-if="batchInfo.type === 2">(中职)</span> -->
                </span>
              </div>
            </div>
            <div class="alitem">
              <el-tooltip effect="dark" content="个人资料" placement="top">
                <el-icon @click="userInfoChange('first')">
                  <Postcard />
                </el-icon>
              </el-tooltip>
              <el-tooltip effect="dark" content="志愿表" placement="top">
                <el-icon class="maginleft20" @click="userInfoChange('fourth3')">
                  <Tickets />
                </el-icon>
              </el-tooltip>
              <el-divider v-if="false" direction="vertical" />
              <el-tooltip
                v-if="false"
                effect="dark"
                content="一键填报"
                placement="top"
              >
                <el-icon class="maginleft10" @click="oneClickToFillIn">
                  <Notebook />
                </el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
      </template>
      <!-- 志愿填报表格数据 -->
      <div v-infinite-scroll="load" id="scrollContainer">
        <!--院校/专业/职业-->
        <div class="alitem">
          <div
            style="margin: 0 10px"
            v-for="(item, idx) in tabslist"
            :key="idx"
            :class="item.id === index ? 'active' : 'tabs'"
            @click="tabsChange(item.id)"
          >
            {{ item.name }}
          </div>
        </div>
        <div v-show="index == 0">
          <schoolDate
            :batch="batchInfo.batch"
            ref="schoolDateinfo"
            :studentId="studentData.studentId"
            :idDrawer="idDrawer"
            :zntbProvinceId="studentData.gkaProvinceNumId"
            :zntbScore="studentInfo.score"
            :schoolData="schoolData"
          ></schoolDate>
        </div>
        <!-- 专业优先=>专业选择 -->
        <div v-show="index == 1">
          <specialty
            ref="majorDataInfo"
            :studentId="studentData.studentId"
            :batchInfo="batchInfo"
            :idDrawer="idDrawer"
            :studentType="studentType"
            :zntbProvinceId="studentData.gkaProvinceNumId"
            :zntbScore="studentInfo.score"
            :specialtyData="specialtyData"
            :subjectName="subjectName"
            @majorEnrollType="majorEnrollType"
            @addMojoyType="addMojoyType"
          ></specialty>
        </div>
        <div v-show="index == 2">
          <career
            ref="jobDataInfo"
            :studentId="studentData.studentId"
            :idDrawer="idDrawer"
            :zntbProvinceId="studentData.gkaProvinceNumId"
            :zntbScore="studentInfo.score"
          ></career>
        </div>
        <!--筛选条件-->
        <div class="screen matop">
          <span class="screenSize">筛选条件:</span>
          <div class="flexwrap">
            <div
              class="screenTab between flexwrap"
              v-for="(item, idx) in userSearchDate"
              :key="idx"
              @click="delChange(idx, item)"
            >
              {{ item.name }}
              <el-icon size="12" style="margin-left: 2px; cursor: pointer">
                <Close />
              </el-icon>
            </div>
          </div>
          <div style="width: 100px"></div>
          <el-icon
            class="curr"
            size="14"
            style="width: 60px; position: absolute; right: 10px"
            @click="onClickDeleteAllSearch"
          >
            <Delete /> 清空
          </el-icon>
        </div>
        <!-- 筛选信息 -->
        <el-row
          v-if="true"
          :gutter="20"
          class="margintop"
          style="margin-left: 0 !important; margin-right: 0 !important"
        >
          <el-col v-if="false" :span="10" class="flex">
            <el-popover
              placement="bottom-start"
              :width="100"
              :trigger="selTypeIndex == 0 ? 'hover' : ''"
            >
              <template #reference>
                <el-button type="primary" @click="onClickTypeItem(0)"
                  >{{
                    zy_type == 1
                      ? selTypeIndex == 0
                        ? chanceTitle
                        : '专业/院校'
                      : chanceTitle
                  }}<samp>&nbsp;</samp>
                  <el-icon size="20">
                    <ArrowDownBold />
                  </el-icon>
                </el-button>
              </template>
              <div class="margintop curr" @click="onClickChanceLvItem(0)">
                {{ (zy_type == 1 ? '专业/院校 ' : '全部 ') + chance_lv_all }}
              </div>
              <div class="margintop curr" @click="onClickChanceLvItem(1)">
                冲 {{ chance_lv_1 }}
              </div>
              <div class="margintop curr" @click="onClickChanceLvItem(2)">
                稳 {{ chance_lv_2 }}
              </div>
              <div class="margintop curr" @click="onClickChanceLvItem(3)">
                保 {{ chance_lv_3 }}
              </div>
            </el-popover>
            <el-popover
              v-if="zy_type == 1"
              placement="bottom-start"
              :width="100"
              :trigger="selTypeIndex == 1 ? 'hover' : ''"
            >
              <template #reference>
                <el-button type="primary" @click="onClickTypeItem(1)">
                  {{ selTypeIndex == 1 ? chanceTitle : '院校/专业'
                  }}<samp>&nbsp;</samp>
                  <el-icon size="20">
                    <ArrowDownBold />
                  </el-icon>
                </el-button>
              </template>
              <div class="margintop curr" @click="onClickChanceLvItem(0)">
                {{ (zy_type == 1 ? '院校/专业 ' : '全部 ') + chance_lv_all }}
              </div>
              <div class="margintop curr" @click="onClickChanceLvItem(1)">
                冲 {{ chance_lv_1 }}
              </div>
              <div class="margintop curr" @click="onClickChanceLvItem(2)">
                稳 {{ chance_lv_2 }}
              </div>
              <div class="margintop curr" @click="onClickChanceLvItem(3)">
                保 {{ chance_lv_3 }}
              </div>
            </el-popover>
            <el-button @click="reportchange">
              <el-icon>
                <Tickets />
              </el-icon>
              推荐报告
            </el-button>
          </el-col>
          <el-col v-if="false" :span="5">
            <div class="right">
              <el-popover
                placement="bottom"
                :width="300"
                :visible="showScreenPopover"
              >
                <template #reference>
                  <el-button
                    @click.stop="showScreenPopover = !showScreenPopover"
                    >高级筛选
                    <el-icon size="20">
                      <ArrowDownBold />
                    </el-icon>
                  </el-button>
                </template>
                <el-form
                  ref="ruleFormRef"
                  label-position="top"
                  :model="requestData"
                  label-width="auto"
                >
                  <el-form-item label="中外合作">
                    <el-radio-group v-model="fType">
                      <el-radio :value="0">全部</el-radio>
                      <el-radio :value="1">仅看中外</el-radio>
                      <el-radio :value="2">不看中外</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="历年征集">
                    <el-radio-group v-model="hasZJ">
                      <el-radio :value="0">全部</el-radio>
                      <el-radio :value="1">仅看征集</el-radio>
                      <el-radio :value="2">不看征集</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <div class="right">
                    <el-button @click="resetForm()">重置</el-button>
                    <el-button type="primary" @click="submitForm()">
                      确定
                    </el-button>
                  </div>
                </el-form>
              </el-popover>
              <span class="recommend">推荐范围</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-slider
              class="slider-score"
              v-model="scoreRange"
              range
              :min="sliderRange[0]"
              :max="sliderRange[1]"
              @change="scoreValueChange"
            />
          </el-col>
        </el-row>
        <!-- 自定义表头 -->
        <div v-if="true" class="classifyheader margintop">
          <!-- 录取概率+院校排名表头 -->
          <div class="flex sizebg">
            <div
              style="margin-left: 40px"
              class="alitem"
              @click="onClickSort('chance')"
              v-if="false"
            >
              录取概率
              <el-icon size="16">
                <SortDown
                  :class="
                    requestData.order == 'chance' && requestData.is_sort
                      ? 'sort-sel'
                      : ''
                  "
                />
                <SortUp
                  :class="
                    requestData.order == 'chance' && !requestData.is_sort
                      ? 'sort-sel'
                      : ''
                  "
                  style="margin-left: -7px"
                />
              </el-icon>
            </div>
            <div
              style="margin-left: 20px"
              class="alitem"
              @click="onClickSort('rank')"
            >
              院校排名
              <el-icon size="16">
                <SortDown
                  :class="
                    requestData.order == 'rank' && requestData.is_sort
                      ? 'sort-sel'
                      : ''
                  "
                />
                <SortUp
                  :class="
                    requestData.order == 'rank' && !requestData.is_sort
                      ? 'sort-sel'
                      : ''
                  "
                  style="margin-left: -7px"
                />
              </el-icon>
            </div>
          </div>
          <!-- 招生计划+历年+填报表头 -->
          <div class="flex sizeinfo">
            <div
              class="alitem"
              style="margin-right: 10px"
              @click="onClickSort('planNum')"
            >
              {{ summary.today_year }}招生计划
              <el-icon size="16">
                <SortDown
                  :class="
                    requestData.order == 'planNum' && requestData.is_sort
                      ? 'sort-sel'
                      : ''
                  "
                />
                <SortUp
                  :class="
                    requestData.order == 'planNum' && !requestData.is_sort
                      ? 'sort-sel'
                      : ''
                  "
                  style="margin-left: -7px"
                />
              </el-icon>
            </div>
            <div style="width: 53px" class="center">历年</div>
            <div style="width: 90px" class="center">
              {{ summary.history_year - 0 }}
            </div>
            <div style="width: 90px" class="center">
              {{ summary.history_year - 1 }}
            </div>
            <div style="width: 90px" class="center">
              {{ summary.history_year - 2 }}
            </div>
            <div style="margin-left: 60px; margin-right: 20px">填报</div>
          </div>
        </div>
        <template v-if="schoolListArr.length == 0">
          <el-empty description="暂无数据" />
        </template>
        <!-- v-loading="isRequest" -->
        <!-- 表格部分 -->
        <div ref="tableViewRef">
          <!-- 所有地区暂时取消选填专业上限 -->
          <!-- :zy_num_group="zy_num_group" -->
          <!--江苏-->
          <jsSchoolList
            v-if="zy_type == 2"
            :schoolListArr="schoolListArr"
            :studentData="studentData"
            :volunteerNumber="volunteerNumber * 1"
            @universityInfo="universityInfo"
            :userSearchDate="userSearchDate"
            :disableUniversityInfo="disableUniversityInfo"
            :highlightTextCollage="highlightTextCollage"
            :highlightTextMajor="highlightTextMajor"
          ></jsSchoolList>
          <!-- 山东 专业/院校-->
          <sdSchoolListMajor
            v-else-if="zy_type == 1 && selTypeIndex == 0"
            :studentData="studentData"
            :schoolListArr="schoolListArr"
            :volunteerNumber="volunteerNumber * 1"
            @universityInfo="universityInfo"
            :userSearchDate="userSearchDate"
            :disableUniversityInfo="disableUniversityInfo"
          >
          </sdSchoolListMajor>
          <!-- 山东 院校/专业-->
          <sdSchoolListCollege
            :studentData="studentData"
            v-else-if="zy_type == 1 && selTypeIndex == 1"
            :schoolListArr="schoolListArr"
            :volunteerNumber="volunteerNumber * 1"
            @universityInfo="universityInfo"
            :userSearchDate="userSearchDate"
            :disableUniversityInfo="disableUniversityInfo"
          >
          </sdSchoolListCollege>

          <scSchoolList
            v-else
            :studentData="studentData"
            :schoolListArr="schoolListArr"
            :volunteerNumber="volunteerNumber * 1"
            @universityInfo="universityInfo"
            :userSearchDate="userSearchDate"
            :disableUniversityInfo="disableUniversityInfo"
          ></scSchoolList>
        </div>
        <div v-show="allDataFetched" class="center" style="margin-top: 20px">
          已加载全部数据
        </div>
        <div
          style="text-align: center; min-height: 30px"
          v-if="!allDataFetched"
        >
          <p v-show="isLoading">加载中...</p>
        </div>
        <div
          style="text-align: center; margin: 20px; cursor: pointer"
          v-if="fail"
          @click="reloadFun"
        >
          加载失败，点击重新加载...
        </div>
        <!-- </el-scrollbar> -->
      </div>
    </el-card>
  </div>
  <!-- 右侧吸附弹窗 -->
  <!-- 江苏 四川 -->
  <jsTypePopup
    ref="typePopupRef"
    v-if="zy_type == 2"
    :studentData="studentData"
    :batchInfo="batchInfo"
    @onClickTop="onClickTop"
  ></jsTypePopup>
  <!--四川-->
  <!-- zy_type != 2 && studentInfo.pid == 51 -->
  <sichuanPopup
    ref="typePopupRef"
    v-if="false"
    :studentData="studentData"
    :batchInfo="batchInfo"
    @onClickTop="onClickTop"
  >
  </sichuanPopup>
  <!--   v-else-if="zy_type == 3" -->
  <scTypePopup
    ref="typePopupRef"
    v-if="false"
    :studentData="studentData"
    :batchInfo="batchInfo"
    @onClickTop="onClickTop"
  ></scTypePopup>
  <!-- 山东-->
  <sdTypePopup
    ref="typePopupRef"
    v-if="false"
    :studentData="studentData"
    :batchInfo="batchInfo"
    @onClickTop="onClickTop"
  >
  </sdTypePopup>
  <userInfoDialog :studentData="studentData" ref="userInfo"></userInfoDialog>
  <reportDialog ref="report"></reportDialog>
  <acceptanceRateDialog ref="acceptanceRate"></acceptanceRateDialog>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router';
import acceptanceRateDialog from '@/views/leader/volunteer/module/acceptanceRateDialog.vue';
import jsTypePopup from './module/jsTypePopup.vue';
import scTypePopup from './module/scTypePopup.vue';
import sichuanPopup from './module/sichuanPopup.vue';
import sdTypePopup from './module/sdTypePopup.vue';
import schoolDate from './module/schoolDate.vue'; // 学校
import career from './module/career.vue'; // 职业
import specialty from './module/specialty.vue'; // 专业
import jsSchoolList from './module/jsSchoolList.vue'; // 江苏
import scSchoolList from './module/scSchoolList.vue'; // 四川
import sdSchoolListMajor from './module/sdSchoolListMajor.vue'; // 山东
import sdSchoolListCollege from './module/sdSchoolListCollege.vue'; // 山东
import userInfoDialog from './module/userInfoDialog.vue';
import reportDialog from './module/reportDialog.vue';

import { schoolEnrollChance } from '@/api/leader/advanceApproval.js';
import userSearch from '@/store/modules/searchInfo.js';
import { onUnmounted } from 'vue';
import volunteersStore from '@/store/modules/volunteerInfos';
import _ from 'lodash';
import bus from '@/utils/bus.js';
import { getLikeList } from '@/api/appv2/appv2';
import { ElMessage } from 'element-plus';
const sgName = {
  物: 1,
  化: 2,
  政: 6,
  史: 4,
  生: 3,
  地: 5,
  技: 7,
};
// 转换选科为sgid
const convertString = (str) => {
  // 1. 将字符串按“/”分割
  const keys = str.split('/');
  // 2. 将分割后的每个元素通过a对象映射转换为对应的值
  const result = keys.map((key) => sgName[key]);
  // 3. 将结果数组转为逗号分隔的字符串
  return result.join(',');
};
const isLoading = ref(false);
const idDrawer = ref(true);
const schoolData = ref({});
const specialtyData = ref({});
const userSearchVal = userSearch(); // 筛选仓库
let userSearchDate = computed(() => userSearchVal.searchArraylist); // 筛选数据

let disableUniversityInfo = computed(() => equivalents.value.length == 0); // 是否能弹窗录取率
const volunteerStore = volunteersStore(); // 志愿表仓库

const schoolDateinfo = ref(null);
const majorDataInfo = ref(null);

const jobDataInfo = ref(null);

const router = useRouter();
const route = useRoute();
const userInfo = ref(null);
const report = ref(null);
const fail = ref(false);

const tabslist = ref([
  {
    id: 0,
    name: '院校优先',
  },
  {
    id: 1,
    name: '专业优先',
  },
  // {
  //   id: 2,
  //   name: '职业优先',
  // },
]);
const studentType = ref([
  '普通类',
  '专项',
  '师范',
  '扶贫',
  '预科',
  '定向',
  '少数名族',
]);
const index = ref(0);
const tableViewRef = ref(null);
const typePopupRef = ref(null);
const allDataFetched = ref(false); // 是否全部加载
const schoolListArr = ref([]); // 填报院校/专业数据列表
const summary = ref({}); // 冲保稳数据
const batchs = ref([]);
const selTypeIndex = ref(0); // 选中的填报类型 0-专业/院校 or 1-院校/专业 山东填报类型或北京专科填报类型才会显示
const zy_type = ref(0); // 填报地区类型 1-山东 2-江苏 3-四川
const volunteerNumber = ref(0); // 可填报志愿表数量
const zy_num_group = ref(0); // 可填报志愿表下专业数量
const chanceTitle = ref(''); // 标题
const chance_lv_1 = ref(0); // 冲数量
const chance_lv_2 = ref(0); // 稳数量
const chance_lv_3 = ref(0); // 保数量
const chance_lv_all = ref(0); // 全部数量
const batchInfo = ref({}); // 选择的批次线信息
const studentData = ref({}); // 选择的学生数据
const studentInfo = ref({}); // 学生信息
const resultCode = ref(null);
const subjectName = ref(''); //判断学历

// 请求数据
const requestData = reactive({
  studentId: '',
  batch: '',
  page: 1,
  pageSize: 10,
  fronttype: 3,
  fType: 0, // 0-全部
  hasZJ: 0, // 0-全部
  order: '', // 排序 chance-录取率 rank-院校排名 planNum-招生计划
  is_sort: false, // 是否升序，false升序，true降序
});
const like = ref({
  type: 'school',
  studentId: localStorage.getItem('student_id'),
  detail: '1',
});
const fType = ref(0);
const hasZJ = ref(0);
const screenData = ref({}); // 筛选数据
const isRequest = ref(false);
const scoreRange = ref([100, 750]); // 选择的分数区间
const sliderRange = ref([100, 750]); // 可选择的分数区间
const showScreenPopover = ref(false); // 是否显示高级筛选弹窗

const equivalents = ref({}); // 线差所需要的年份集合

// 限报要求
const enrollTags = ref({
  isRestrictColorBW: false,
  isRestrictScore: false,
  isRestrictLanguage: false,
});

// 定义防抖后的函数
const debouncedGetSchoolEnrollChance = debounce(getSchoolEnrollChance, 500);

const majorEnrollType = (val) => {
  requestData.majorEnrollTypes = val.majorEnrollTypes;
  requestData.enrollmentType = val.enrollmentType;

  debouncedGetSchoolEnrollChance();
};
const addMojoyType = (val) => {
  requestData.mojoyType = val;

  debouncedGetSchoolEnrollChance();
};

// 处理数据，显示报考要求
bus.on('changeMajorEnrollTypes', (data) => {
  enrollTags.value[data.key] = data.val;
  addStatus();
});

// 添加报考要求
const addStatus = () => {
  schoolListArr.value.forEach((item) => {
    if (
      item.enrollTags?.isRestrictColorBW &&
      enrollTags.value.isRestrictColorBW
    ) {
      item.majorEnrollTypesLable = '有限报要求';
    } else if (
      item.enrollTags?.isRestrictScore &&
      enrollTags.value.isRestrictScore
    ) {
      item.majorEnrollTypesLable = '有限报要求';
    } else if (
      item.enrollTags?.isRestrictLanguage &&
      enrollTags.value.isRestrictLanguage
    ) {
      item.majorEnrollTypesLable = '有限报要求';
    } else {
      item.majorEnrollTypesLable = '';
    }

    item.majorsInfo?.forEach((major) => {
      if (
        major.enrollTags?.isRestrictColorBW &&
        enrollTags.value.isRestrictColorBW
      ) {
        major.majorEnrollTypesLable = '有限报要求';
      } else if (
        major.enrollTags?.isRestrictScore &&
        enrollTags.value.isRestrictScore
      ) {
        major.majorEnrollTypesLable = '有限报要求';
      } else if (
        major.enrollTags?.isRestrictLanguage &&
        enrollTags.value.isRestrictLanguage
      ) {
        major.majorEnrollTypesLable = '有限报要求';
      } else {
        major.majorEnrollTypesLable = '';
      }
    });
  });
};

watch(
  // 监听院校筛选数据改变
  () => userSearchDate.value,
  () => {
    schoolSearchDataChange();
  }
);

bus.emit('handlePathTextChange', '志愿填报');

onBeforeRouteLeave((to, from, next) => {
  bus.emit('handlePathTextChange', '');
  next();
});
//获取关注的院校
const getLikeListData = () => {
  getLikeList(like.value).then((res) => {
    if (res.code == 20000) {
      schoolData.value = res.data?.schoolDetail.map((item) => {
        return {
          ...item, // 保留原有的属性
          isChange: false, // 添加新属性 gbCode
        };
      });
      specialtyData.value = Array.isArray(res.data?.majorDetail)
        ? res.data.majorDetail.map((item) => {
            return {
              ...item, // 保留原有的属性
              isChange: false, // 添加新属性
            };
          })
        : []; // 如果不是数组，则赋值空数组
    } else {
      console.log(res);
    }
  });
};
getLikeListData();
// 院校筛选数据改变
function schoolSearchDataChange() {
  let searchData = {
    province: [],
    categories: [],
    features: [],
    natureType: [],
    eduLevelSchool: [],
    schoolNewly: [],
    scode: [],
    mcode: [],
    zcode: [],
    ssearch: '',
    msearch: '',
    zsearch: '',
  };

  for (let item of userSearchDate.value) {
    switch (item.type) {
      case 'province':
        searchData.province.push(item.code);
        break;
      case 'type':
        searchData.categories.push(item.name);
        break;
      case 'school_feature':
        searchData.features.push(item.name);
        break;
      case 'nature':
        searchData.natureType.push(item.code);
        break;
      case 'school_type':
        searchData.eduLevelSchool.push(item.code);
        break;
      case 'schoolNewly':
        searchData.schoolNewly.push(item.code);
        break;
      case 'schoolSearch':
        searchData.scode.push(item.code);
        break;
      case 'major':
        searchData.mcode.push(item.code);
        break;
      case 'job':
        searchData.zcode.push(item.code);
        break;
      case 'ssearch':
        searchData.ssearch = item.name;
        break;
      case 'msearch':
        searchData.msearch = item.name;
        break;
      case 'zsearch':
        searchData.zsearch = item.name;
    }
  }

  let data = {
    province: searchData.province.toString(),
    categories: searchData.categories.toString(),
    features: searchData.features.toString(),
    natureType: searchData.natureType.toString(),
    eduLevelSchool: searchData.eduLevelSchool.toString(),
    schoolNewly: searchData.schoolNewly.toString(),
    scode: searchData.scode.toString(),
    mcode: searchData.mcode.toString(),
    zcode: searchData.zcode.toString(),
    ssearch: searchData.ssearch,
    msearch: searchData.msearch,
    zsearch: searchData.zsearch,
  };
  screenData.value = data;

  debouncedGetSchoolEnrollChance(1);
}

init();
// 初始化
function init() {
  let data = {};

  try {
    userSearchVal.delAllSearchInfo();
    data = JSON.parse(decodeURIComponent(atob(route.query.data)));
    subjectName.value = data.batchInfo?.batch;
    batchInfo.value = data.batchInfo;
    console.log(batchInfo.value.batch, 'batchbatch');

    batchInfo.value.batch =
      localStorage.getItem('zhigao') == 1 ? '高职单招' : '中职单招';
    studentData.value = data.studentData;
    studentInfo.value = data.studentData.student;
    console.log(
      batchInfo.value,
      ' batchInfo.value',
      localStorage.getItem('zhigao')
    );

    requestData.studentId = studentData.value.studentId;
    // requestData.batch = batchInfo.value.batch;
    requestData.batch =
      localStorage.getItem('zhigao') == 1 ? '高职单招' : '中职单招';

    if (!data.update) {
      // 重置仓库中志愿表数据
      volunteerStore.setVolunteerInfos([]);
    }

    debouncedGetSchoolEnrollChance();
  } catch (e) {
    // 加入这个容错的目的是防止有些用户在进入这张页面不小心改了地址栏浏览器参数的问题
    //因为这套代码之前的人用地址栏传参，还传了大量的参数，换其他方法成本太大
    setTimeout(() => {
      console.log(e, '错误信息');
      ElMessage({
        message: '参数错误，2S之后自动返回上一级',
        type: 'warning',
      });
      setTimeout(() => {
        router.push({ path: '/leader/Filling' }).then(() => {
          window.location.reload(); // 刷新页面
        });
      }, 2000);
    }, 200);

    return;
  }
}

// 返回
function onClickBack() {
  router.back();
}

// 回到顶部
function onClickTop() {
  const scrollContainer = document.querySelector('.el-card__body');
  scrollContainer.scrollTo({
    top: 0,
    behavior: 'smooth',
  });
}

let scrollFlag = ref(false);
const load = () => {
  // 获取滚动容器的信息

  if (isLoading.value) return; // 如果请求失败，则不执行后续操作
  isLoading.value = true;
  if (!allDataFetched.value) {
    if (resultCode.value == 20000 && !isRequest.value) {
      requestData.page += 1;
      scrollFlag.value = true;
      debouncedGetSchoolEnrollChance();
    }
  }
};

//录取率弹窗
const acceptanceRate = ref(null);
const universityInfo = (data, isMajor) => {
  acceptanceRate.value.open(data, isMajor, equivalents, batchs);
};
// 加载失败page-1重新加载
const reloadFun = () => {
  isRequest.value = false;
  debouncedGetSchoolEnrollChance(requestData.page);
};

// 防抖函数
function debounce(func, wait) {
  let timeout; // 定时器

  return function (...args) {
    clearTimeout(timeout); // 清除之前的定时器
    timeout = setTimeout(() => {
      func.apply(this, args); // 在 wait 时间后执行目标函数
    }, wait);
  };
}

/**
 * 获取填报列表
 * @param {Object} page 页码 可选参数，用于page=1 滚动的时候不清空列表，其他时候都清空列表
 */
function getSchoolEnrollChance(page) {
  if (page) requestData.page = page;

  let data = {
    ...requestData,
    ...screenData.value,
  };

  if (selTypeIndex.value == 1) {
    data['zy_type'] = 3;
  }
  if (scoreRange.value.length >= 2) {
    data['score_min'] = scoreRange.value[0];
    data['score_max'] = scoreRange.value[1];
  }
  console.log(scoreRange.value, '请求参数');

  // Object.keys(data).forEach((key) => {
  //   if (data[key].length == 0) {
  //     delete data[key];
  //   }
  // });

  isLoading.value = true;

  console.log(data, 'data123,');

  if (batchInfo.value.score) {
    data['score'] = batchInfo.value.score;
    data['sgid'] = convertString(batchInfo.value.sgname);
    data['batch'] = convertString(batchInfo.value.batch);
    data['course'] = localStorage.getItem('course');
  } else {
    data['sgid'] = convertString(studentInfo.value.sgname);
    data['score'] = studentInfo.value.score;
    data['course'] = localStorage.getItem('courseNew');
  }

  schoolEnrollChance(data)
    .then((res) => {
      if (res.code == 20000) {
        localStorage.setItem('courseNew', res.data.course || '');

        fail.value = false;
        resultCode.value = res.code;
        isLoading.value = false;

        isRequest.value = false;
        const data = res.data || {};

        // scrollFlag.value 如果这个===true,说明是滚动列表，否者都不是滚动列表，其他情况下都要重置当前页和原数组
        if (scrollFlag.value) {
          scrollFlag.value = false;
        } else {
          schoolListArr.value = [];
        }

        equivalents.value = data.equivalents;

        allDataFetched.value = data.list.length == 0;

        summary.value = data.summary;
        batchs.value = data.batchs;
        console.log(data, 'datadata');

        // sliderRange.value[0] = data.summary.score_min_m || 0;
        // sliderRange.value[1] = data.summary.score_max_m || 750;
        // scoreRange.value[0] = data.summary.score_min||0;
        // scoreRange.value[1] = data.summary.score_max||750;

        if (requestData.page == 1) {
          schoolListArr.value = [];
        }

        schoolListArr.value = [...schoolListArr.value, ...data.list];
        console.log(schoolListArr.value, '单招数据-原始数据');
        // 这段代码之后可注释，作用只是为了吧2025,2023年的数据渲染出来，之所以这样干，是因为前人写的代码结构改动的成本太高了 不想动

        // schoolListArr.value.forEach((item) => {
        //   if (item.moreYear.length == 1) {
        //     console.log(item.moreYear[0], 'item.moreYear[0]');
        //     item.moreYear.push({
        //       ...item.moreYear[0],
        //       year: '2025',
        //       enterNum: 0,
        //     });

        //     // 添加 2023 年的数据
        //     item.moreYear.push({
        //       ...item.moreYear[0],
        //       year: '2023',
        //       enterNum: 0,
        //     });

        //     // 按照 year 字段降序排序
        //     item.moreYear.sort((a, b) => b.year - a.year);
        //   }
        //   item.majorsInfo.forEach((val) => {
        //     if (val.moreYear.length == 1) {
        //       val.moreYear.push({
        //         ...item.moreYear[0],
        //         year: '2025',
        //         enterNum: 0,
        //       });

        //       // 添加 2023 年的数据
        //       val.moreYear.push({
        //         ...item.moreYear[0],
        //         year: '2023',
        //         enterNum: 0,
        //       });

        //       // 按照 year 字段降序排序
        //       val.moreYear.sort((a, b) => b.year - a.year);
        //     }
        //   });
        // });
        console.log(schoolListArr.value, '单招数据-处理后的数据');

        addStatus();
        volunteerNumber.value = data.zy_info.zy_num;
        zy_type.value = data.zy_info.zy_type;

        zy_num_group.value = data.zy_info.zy_num_group;
        chance_lv_1.value = data.summary.chance_lv_1 || 0;
        chance_lv_2.value = data.summary.chance_lv_2 || 0;
        chance_lv_3.value = data.summary.chance_lv_3 || 0;
        chance_lv_all.value =
          chance_lv_1.value + chance_lv_2.value + chance_lv_3.value;

        for (const v of schoolListArr.value) {
          for (const vv of v.moreYear) {
            // 判断是否显示等效位差
            if (vv.hasPlan) {
              // equivalents.value  为空的时候是个数组，有值的时候是个对象
              if (equivalents.value.length == 0) {
                vv.equivalentBitDifference = '-';
              } else if (equivalents.value[vv.year].eqRank) {
                if (!!vv.minRank && vv.minRank !== 0 && vv.minRank !== '-') {
                  // equivalentBitDifference 等效位差
                  vv.equivalentBitDifference =
                    vv.minRank - equivalents.value[vv.year].eqRank;
                } else {
                  vv.equivalentBitDifference = '-';
                }
              } else {
                vv.equivalentBitDifference = '-';
              }
            } else {
              vv.equivalentBitDifference = '-';
            }
          }
          for (const vv of v.majorsInfo) {
            for (const vvv of vv.moreYear) {
              // 判断是否显示等效位差
              if (vvv.hasPlan) {
                // equivalents.value  为空的时候是个数组，有值的时候是个对象
                if (equivalents.value.length == 0) {
                  vvv.equivalentBitDifference = '-';
                } else if (equivalents.value[vvv.year].eqRank) {
                  if (
                    !!vvv.minRank &&
                    vvv.minRank !== 0 &&
                    vvv.minRank !== '-'
                  ) {
                    vvv.equivalentBitDifference =
                      vvv.minRank - equivalents.value[vvv.year].eqRank;
                  } else {
                    vvv.equivalentBitDifference = '-';
                  }
                } else {
                  vvv.equivalentBitDifference = '-';
                }
              } else {
                vvv.equivalentBitDifference = '-';
              }
            }
          }
        }

        refreshChanceTitle(requestData.chance_lv || 0);
      } else {
        console.log('打印失败');

        fail.value = true;
        if (res.code == 44444) {
          router.go(-1);
        } else {
          isLoading.value = false;
          fail.value = true;
          isRequest.value = true;
          // allDataFetched.value = false; //控制是否加载全部数据
          resultCode.value = -1;
        }
      }
    })
    .catch((error) => {
      fail.value = true;
      if (error.name === 'AbortError') {
        console.log('请求被取消');
      } else {
        resultCode.value = error.code;
        isLoading.value = false;
        isRequest.value = false;
        allDataFetched.value = false;
      }
    });
}

/**
 * 点击切换录取率筛选项
 * @param {Number} tag 0-全部 1-冲 2-稳 3-保
 */
function onClickChanceLvItem(tag) {
  if (requestData.chance_lv != tag) {
    requestData.chance_lv = tag;

    refreshChanceTitle(tag);

    debouncedGetSchoolEnrollChance(1);
  }
}

/**
 * 刷新录取率筛选标题
 * @param {Number} tag 0-全部 1-冲 2-稳 3-保
 */
function refreshChanceTitle(tag) {
  switch (tag) {
    case 0:
      if (selTypeIndex.value == 0) {
        chanceTitle.value =
          (zy_type.value == 1 ? '专业/院校 ' : '全部 ') + chance_lv_all.value;
      } else {
        chanceTitle.value =
          (zy_type.value == 1 ? '院校/专业 ' : '全部 ') + chance_lv_all.value;
      }
      break;
    case 1:
      chanceTitle.value = '冲' + chance_lv_1.value;
      break;
    case 2:
      chanceTitle.value = '稳' + chance_lv_2.value;
      break;
    case 3:
      chanceTitle.value = '保' + chance_lv_3.value;
  }
}

/**
 * 点击切换排序
 * @param {Object} type chance-录取率 rank-院校排名 planNum-招生计划
 */
function onClickSort(type) {
  if (requestData.order == type) {
    requestData.is_sort = !requestData.is_sort;
  } else {
    requestData.is_sort = false;
  }
  requestData.order = type;

  debouncedGetSchoolEnrollChance(1);
}

// 分数区间改变
const scoreValueChange = _.throttle(() => {
  debouncedGetSchoolEnrollChance(1);
}, 800);

// 删除筛选条件信息
function delChange(idx, item) {
  if (item.type == 'major' || item.type == 'msearch') {
    // 专业
    if (item.code.length == 6) {
      headDeleteItemBtn(item);
    } else {
      majorDataInfo.value.deleteScreenItem(item);
    }
  } else if (item.type == 'job' || item.type == 'zsearch') {
    // 职业
    jobDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'fType' || item.type == 'hasZJ') {
    // 高级
    item.type == 'fType' ? (fType.value = 0) : (hasZJ.value = 0);
    submitForm();
  } else {
    // 院校
    schoolDateinfo.value.deleteScreenItem(item);
  }
}

const headDeleteItemBtn = (item) => {
  majorDataInfo.value.deleteScreenItem(item);
};

// 删除全部筛选数据
// 防抖
const onClickDeleteAllSearch = _.debounce(() => {
  if (userSearchDate.value.length > 0) {
    majorDataInfo.value.deleteAll();
    jobDataInfo.value.deleteAll();
    schoolDateinfo.value.deleteAll();
  }
}, 800);

// 院校-名称-高亮
const userSearchDateString1 = ref([]);
// 专业-名称-高亮
const userSearchDateString2 = ref([]);

watchEffect(() => {
  userSearchDateString1.value = userSearchDate.value.map((item) => item.name);
  // 提取 props.userSearchDate 中每一项的 code 的前四位
  userSearchDateString2.value = userSearchDate.value.map((item) =>
    item.code.slice(0, 4)
  );
});

// 用来转义正则表达式中的特殊字符
const escapeRegExp1 = (str) => {
  return str.replace(/[.*+?^=!:${}()|\[\]\/\\]/g, '\\$&'); // 转义所有正则特殊字符
};
// 用来转义正则表达式中的特殊字符
const escapeRegExp2 = (str) => {
  return str.replace(/[.*+?^=!:${}()|\[\]\/\\]/g, '\\$&'); // 转义所有正则特殊字符
};
// 院校-名称-高亮
const highlightTextCollage = (text) => {
  // console.log(text, '院校亮');
  if (userSearchDateString1.value.length === 0) return text; // 没有选中标签时直接返回原文本
  // 对每个选中的标签进行转义，确保特殊字符不会干扰正则构建
  const escapedStrings = userSearchDateString1.value.map(escapeRegExp1);
  // 使用 | 作为正则的 OR 操作符，构建最终的正则表达式
  const regex = new RegExp(`(${escapedStrings.join('|')})`, 'gi');
  // 使用正则表达式高亮文本
  return text.replace(
    regex,
    '<span style="color: #409eff; font-weight: bold;">$&</span>' // 高亮匹配到的部分
  );
};
// 专业-名称-高亮
const highlightTextMajor = (name, code) => {
  if (userSearchDateString2.value.length === 0) return name; // 没有选中标签时直接返回原文本

  // 截取 code 的前四位（如果 code 是 6 位）
  // const truncatedCode = code.length === 4 ? code.slice(0, 2) : code;
  const truncatedCode = code.slice(0, 2);

  // 对每个选中的标签进行转义，确保特殊字符不会干扰正则构建
  let escapedStrings = userSearchDateString2.value.map(escapeRegExp2);
  escapedStrings = escapedStrings.map((str) => str.slice(0, 2));

  // 使用 | 作为正则的 OR 操作符，构建最终的正则表达式
  const regex = new RegExp(`(${escapedStrings.join('|')})`, 'gi');

  // 检查截取后的 code 是否匹配
  if (regex.test(truncatedCode)) {
    // 如果匹配，高亮 name
    return `<span style="color: #409eff; font-weight: bold;">${name}</span>`;
  } else {
    // 如果不匹配，返回原 name
    return name;
  }
};

/**
 * 点击切换填报类型
 * @param {Number} index 0-专业/院校  1-院校/专业
 */

function onClickTypeItem(index) {
  if (selTypeIndex.value != index) {
    selTypeIndex.value = index;
    schoolListArr.value = [];
    chanceTitle.value = index == 0 ? '专业/院校' : '院校/专业';
    scrollFlag = true;
    getSchoolEnrollChance(1);
    debouncedGetSchoolEnrollChance(1);
  }
}

// 推荐报告
function reportchange() {
  report.value.openChange(summary.value);
}

function userInfoChange(val) {
  userInfo.value.openChange(val);
}

// 一键填报
function oneClickToFillIn() {
  let data = {
    ...requestData,
    ...screenData.value,
  };

  data['auto'] = 1;
  if (selTypeIndex.value == 1) {
    data['zy_type'] = 3;
  }
  if (scoreRange.value.length >= 2) {
    data['score_min'] = scoreRange.value[0];
    data['score_max'] = scoreRange.value[1];
  }

  if (batchInfo.value.score) {
    data['score'] = batchInfo.value.score;
    data['sgid'] = convertString(batchInfo.value.sgname);
    data['batch'] = batchInfo.value.batch;
    data['course'] = localStorage.getItem('course');
  } else {
    data['score'] = studentInfo.value.score;
    data['sgid'] = convertString(studentInfo.value.sgname);
    data['course'] = localStorage.getItem('courseNew');
  }
  if (isRequest.value) return;
  isRequest.value = true;
  schoolEnrollChance(data)
    .then((res) => {
      localStorage.setItem('courseNew', res.data.course || '');

      isRequest.value = false;
      const data = res.data || {};

      if (zy_type.value == 3) {
        data.list.forEach((item, index) => {
          // 将hash值转换为大写英文字母
          let key = String.fromCharCode(index + 65);

          item.vkey = key;
        });
      }

      volunteerStore.setVolunteerInfos(data.list);
      typePopupRef.value.unfoldChange();
    })
    .catch(() => {
      isRequest.value = false;
    });
}

// 重置高级筛选
function resetForm() {
  fType.value = 0;
  hasZJ.value = 0;
}

// 提交高级筛选
function submitForm() {
  if (requestData.fType != fType.value || requestData.hasZJ != hasZJ.value) {
    requestData.fType = fType.value;
    requestData.hasZJ = hasZJ.value;

    let arr = [];
    if (requestData.fType != 0) {
      arr.push({
        name: requestData.fType == 1 ? '仅看中外' : '不看中外',
        code: requestData.fType,
        type: 'fType',
      });
    }

    if (requestData.hasZJ != 0) {
      arr.push({
        name: requestData.hasZJ == 1 ? '仅看征集' : '不看征集',
        code: requestData.hasZJ,
        type: 'hasZJ',
      });
    }

    userSearchVal.saveAdvancedInfoChange(arr);
    showScreenPopover.value = false;
  }
}

function tabsChange(idx) {
  index.value = idx;
  schoolDateinfo.value.closeV();
  majorDataInfo.value.closeV();
  if (idx == 0) {
    like.value.type = 'school';
  } else if (idx == 1) {
    like.value.type = 'marjor';
  } else if (idx == 2) {
    like.value.type = 'job';
  }
  getLikeListData();
}

// 列表滚动的时候 page需要加1
function handleScroll() {
  if (!allDataFetched.value) {
    const table = tableViewRef.value;
    if (table) {
      const scrollBottom =
        table.getBoundingClientRect().bottom - window.innerHeight;
      if (scrollBottom <= -41) {
        requestData.page += 1;
        debouncedGetSchoolEnrollChance();
      }
    }
  }
}

function removeScrollListener() {
  window.removeEventListener('scroll', handleScroll);
}

onMounted(() => {
  console.log(zy_type.value, 'zy_type');

  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  removeScrollListener();
});
</script>

<style lang="scss" scoped>
.recommend {
  display: inline-block;
  font-weight: 400;
  color: #4e5969;
  line-height: 14px;
  margin-left: 20px;
  font-size: 14px;
}
.classifyheader {
  background: #fafafa;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #86909c;
  letter-spacing: 0;
  line-height: 28px;
  padding-right: 80px;

  .sort-sel {
    color: #004cf7;
  }
}

.screen {
  min-height: 50px;
  padding: 6px 0 6px 20px;
  background-color: #f9f9f9;
  display: flex;
  overflow: hidden;
  align-items: center;
  position: relative;

  .screenSize {
    font-size: 12px;
    font-weight: 400;
    color: #3d3d3d;
    min-width: 55px;
  }

  .screenTab {
    padding: 7px 10px;
    margin: 2px 0;
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-left: 10px;
  }
}

.box-card {
  margin: 20px;
  width: auto;
  height: calc(100vh - 110px);
  overflow-y: auto;

  .tabs {
    color: #000000;
    font-weight: 600;
    cursor: pointer;
  }

  .active {
    color: #004cf7;
    font-weight: 600;
    cursor: pointer;
  }

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .userInfo {
      margin-left: 30px;
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
      line-height: 16px;

      span {
        margin-left: 8px;
      }
    }

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

// 改变滑块原点大小和颜色  el-slider__button
:deep() .el-slider__button {
  color: red;
  width: 40px;
  height: 30px;
  border-radius: 10px;
  z-index: 1;
  top: var(--el-slider-button-wrapper-offset);
  // transform: translateX(-50%);
  background-color: #fff;
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  line-height: normal;
  outline: 0;
}

// 更改 el-slider__button-wrapper
:deep() .el-slider__button-wrapper {
  height: var(--el-slider-button-wrapper-size);
  width: var(--el-slider-button-wrapper-size);
  position: absolute;
  z-index: 1;
  top: var(--el-slider-button-wrapper-offset);
  transform: translateX(0); // 去掉滑块默认X轴翻转
  background-color: transparent;
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  line-height: normal;
  outline: 0;
}

// 滑块中间显示内容
:deep() .el-slider__button-wrapper::before {
  content: attr(aria-valuetext); // !!显示的内容,注意,一定是这个
  position: absolute;
  width: 20px;
  height: 25px;
  line-height: 25px;
  border-radius: 5px;
  text-align: center;
  top: 4px;
  left: 8.5px;
  font-size: 12px;
  z-index: 999;
}

// 去掉滑块默认鼠标移入事件
:deep() .el-slider__button-wrapper.hover {
  transform: none;
}

:deep() .el-slider__button-wrapper::hover {
  transform: none;
}

:deep() .el-slider__button.hover {
  transform: none;
}

:deep() .el-slider__button::hover {
  transform: none;
}

// 去掉input 边框和输入聚焦
// :deep() .el-input__wrapper {
//     display: inline-flex;
//     flex-grow: 1;
//     align-items: center;
//     justify-content: center;
//     padding: 1px 11px;
//     background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
//     background-image: none;
//     border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
//     cursor: text;
//     transition: var(--el-transition-box-shadow);
//     transform: translate3d(0,0,0);
//     box-shadow: none;
// }

// :deep() .el-input__wrapper.is-focus{
//   box-shadow: none;
// }

// :deep() .el-input__wrapper:hover{
//   box-shadow: none;
// }
</style>

<style lang="scss">
.ctea {
  .el-card__header {
    position: sticky;
    top: 0;
    z-index: 98;
    background-color: white;
  }
  .el-card__body::-webkit-scrollbar {
    width: 8px; /* 加粗的滚动条 */
    display: block;
  }
}
</style>
